package com.kedacom.ctsp.authz.security.provider;

import com.google.common.collect.Sets;
import com.kedacom.ctsp.authz.entity.AuthResource;
import com.kedacom.ctsp.authz.entity.AuthRole;
import com.kedacom.ctsp.authz.entity.Authentication;
import lombok.Getter;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**
 * 用户权限对象
 *
 * @author xuwei
 * @create 2017-11-28 19:30
 **/
public class AuthUserDetails implements UserDetails {

    protected Set<SimpleGrantedAuthority> authorities;
    private String defaultRolePrefix = "ROLE_";
    @Getter
    private Authentication authentication;

    public AuthUserDetails(Authentication authentication) {
        this.authentication = authentication;
    }

    public AuthUserDetails(Authentication authentication, String defaultRolePrefix) {
        this.authentication = authentication;
        this.defaultRolePrefix = defaultRolePrefix;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return authorities;
    }

    public Set<AuthRole> getRoles() {
        return authentication.getRoles();
    }


    @Override
    public String getPassword() {
        return authentication.getPassword();
    }

    @Override
    public String getUsername() {
        return authentication.getUser().getUsername();
    }


    @Override
    public boolean isAccountNonExpired() {
        return authentication.getUser().isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return authentication.getUser().isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return authentication.getUser().isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return authentication.getUser().isEnabled();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        AuthUserDetails that = (AuthUserDetails) o;

        return authentication.equals(that.authentication);
    }

    @Override
    public int hashCode() {
        return authentication.hashCode();
    }

    @Override
    public String toString() {
        return getUsername();
    }
}
